package org.springsecuritylearn.repository.jvm.lession1.demo1;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;

/**
 * @author hyf
 * @Title: ${file_name}
 * @Package org.springsecuritylearn.repository.jvm.lession1.demo1
 * @Description: ${todo}
 * @date 2018/5/4下午11:33
 */
public class SoftRefQ {

    public static class User {
        public int id;
        public String name;

        public byte[] bytes;

        public User(int id, String name) {
            this.id = id;
            this.name = name;
        }

        public User(int id, String name, byte[] bytes) {
            this.id = id;
            this.name = name;
            this.bytes = bytes;
        }
    }

    static ReferenceQueue<User> userReferenceQueue = null;

    public static class CheckRefQueue extends Thread {
        @Override
        public void run() {
            while (true) {
                if (userReferenceQueue != null) {
                    UserSoftReference obj = null;
                    try {
                        obj = (UserSoftReference) userReferenceQueue.remove();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (obj != null) {
                        System.out.println("user id" + obj.uid + " is delete");
                    }
                }
            }
        }
    }


    public static class UserSoftReference extends SoftReference<User> {

        int uid;

        public UserSoftReference(User referent, ReferenceQueue<? super User> q) {
            super(referent, q);
            uid = referent.id;
        }
    }


    public static void main(String[] args) throws InterruptedException {
        Thread t = new CheckRefQueue();
        t.setDaemon(true);
        t.start();
        User u = new User(1, "gg", new byte[1024 * 927 * 2]);
        userReferenceQueue = new ReferenceQueue<User>();
        UserSoftReference userSoftReference = new UserSoftReference(u, userReferenceQueue);
        u = null;
        System.out.println(userSoftReference.get());
        System.gc();

        System.out.println("After:GC");
        System.out.println(userSoftReference.get());
        System.out.println("try to create byte array and GC");


        byte[] b = new byte[1024 * 927 * 7];
        System.gc();
        System.out.println(userSoftReference.get());
        Thread.sleep(1000);

    }


}
